package lsl.leetCode.year2023.test0202;

/**
 * description:
 *
 * @author: liushengli
 * data: 2023/2/2
 */
public class test34 {
    public static void main(String[] args) {
    /*    int[] nums = {5, 7, 7, 8, 8, 10};
        int target = 8;*/
        int[] nums = {2, 2};
        int target = 2;
        searchRange(nums, target);
    }

    public static int[] searchRange(int[] nums, int target) {
        if (nums.length == 0) {
            return new int[]{-1, -1};
        }
        boolean lower = true;
        int leftIndex = search(nums, target, lower);
        int rightIndex = search(nums, target, false);
        if (nums[leftIndex] == target && nums[rightIndex] == target) {
            return new int[]{leftIndex, rightIndex};
        }
        return new int[]{-1, -1};
    }

    public static int search(int[] nums, int target, boolean lower) {
        int left = 0;
        int right = nums.length - 1;
        int result = 0;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                if (lower) {
                    //获取leftIndex---需要继续向左遍历，防止该坐标的值为右坐标的值
                    right = mid - 1;
                    result = mid;
                } else {
                    //获取rightIndex---需要继续向右遍历，防止该坐标的值为左坐标的值
                    left = mid + 1;
                    result = mid;
                }
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return result;
    }
}
